package com.hosp.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;

/**
 * @author caogongde
 * @date 2020/8/13 10:57
 */
public class ExcelUtil2 {

    /**
     * 单个sheet 导出
     *
     * @param response
     * @param fileName  文件名
     * @param sheetName sheet名
     * @param clazz
     * @param data      导出数据
     * @throws IOException
     */
    public static void exportExcel(HttpServletResponse response,
                                   String fileName,
                                   String sheetName,
                                   Class<?> clazz,
                                   List<?> data) throws IOException {
        // 这里注意 有同学反应使用 swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), clazz).sheet("模板").doWrite(data);
    }

    /**
     * 多 sheet 页导出
     *
     * @param response
     * @param fileName
     * @param clazz
     * @param list
     * @param sheetNames
     */
    public static void exportExcelMoreSheets(HttpServletResponse response,
                                             String fileName,
                                             Class<?> clazz,
                                             List<?> list, List<String> sheetNames) {
        ExcelWriter excelWriter = null;
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        try {
            excelWriter = EasyExcel.write(response.getOutputStream()).build();
            fileName = fileName + System.currentTimeMillis() + ".xlsx";
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            for (int i = 0; i < list.size(); i++) {
                WriteSheet writeSheet = EasyExcel.writerSheet(i, sheetNames.get(i)).head(clazz).build();
                List<Object> Object = (List<java.lang.Object>) list.get(i);
                excelWriter.write((List) list.get(i), writeSheet);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }
    }
}